<?php

namespace App\Admin\Forms;

use App\Admin\Renderable\MerchantRenderable;
use App\Models\SwtMerchant;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use App\Models\SwtMerchantMachine;
use Illuminate\Support\Facades\DB;

class SelectedMerchantForm extends Form implements LazyRenderable
{
    use LazyWidget;

    // 处理请求
    public function handle(array $input)
    {
        $id = $input['machine_id'];
        Db::beginTransaction();

        try {
            $owner = SwtMerchantMachine::where('machine_id', $id) -> where('is_owner', 1) -> first();

            if($owner) {
                $deposit = SwtMerchant::where('id', $owner['merchant_id']) -> value('deposit');
                foreach($input['column_name'] as $k => $v) {
                    $input['column_name'][$k]['machine_id'] = $id;

                    if($v['is_owner'] != 1) {
                        $input['column_name'][$k]['deposit_now'] = 0;
                        continue;
                    }

                    if($owner['merchant_id'] == $v['merchant_id']) {
                        $input['column_name'][$k]['deposit_now'] = $owner['deposit_now'];
                        continue;
                    }

                    if($owner['deposit_now'] < $deposit) {
                        throw new \Exception('货款小于预设时无法变更机主');
                    } else {
                        $deposit = SwtMerchant::where('id', $v['merchant_id']) -> value('deposit');
                        $input['column_name'][$k]['deposit_now'] = $deposit;
                    }
                }
            } else {
                foreach($input['column_name'] as $k => $v) {
                    $input['column_name'][$k]['machine_id'] = $id;
                    if($v['is_owner'] == 1) {
                        $deposit = SwtMerchant::where('id', $v['merchant_id']) -> value('deposit');
                        $input['column_name'][$k]['deposit_now'] = $deposit;
                    } else {
                        $input['column_name'][$k]['deposit_now'] = 0;
                    }
                }
            }
            SwtMerchantMachine::where('machine_id', $id) -> delete();

            if(key_exists('column_name', $input) && count($input['column_name']) > 0) {
                $res = SwtMerchantMachine::insert($input['column_name']);

                if(!$res) {
                    throw new \Exception('编辑失败');
                }

                unset($input["column_name"]);
            }


            Db::commit();
            return $this->response()->success('编辑成功')->refresh();
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->response()->error($e->getMessage());
        }
    }


    public function form()
    {
        $this -> hidden('machine_id');

        $this -> table('column_name','', function(Form $form) {
            $default = $form -> model() -> column_name;

            $ids = [];

            if($default) {
                $ids = array_column($default, 'merchant_id');
            }

            $key = $form -> getKey();

            $info = "";

            if($key !== null) {
                $info = $default[$key]['merchant_id'];
            }

            $form -> selectTable('merchant_id','用户')
                -> title('用户表')
                -> from(MerchantRenderable::make(['ids' => $ids,'id' => $info]))
                -> rules('required', [ 'required' => '用户不能为空'])
                -> model(SwtMerchant::class, 'id', 'name')
                -> required();

            $form -> text('percent','分润')
                -> type('number')
                -> rules('required', [ 'required' => '分润比不能为空'])
                -> attribute('min', 0)
                -> attribute('max', 100)
                -> required();

            $form -> switch('is_owner','机主');

        }) -> saving(function ($data) {
            if(!empty($data)) {
                $merchant_ids = array_unique(array_column($data, 'merchant_id'));
                if(count($data) !== count($merchant_ids)) throw new \Exception('商户重复');

                $is_owners = array_unique(array_column($data, 'is_owner'));
                if(count($data) !== count($is_owners)) throw new \Exception('机主不能超过1个');

                $percent = array_sum(array_column($data, 'percent'));
                if($percent > 100) throw new \Exception('分润比不能超过100%');
            }

            return $data;
        });
    }


    public function default()
    {
        $id = $this->payload['id'];

        $machine_user_list = SwtMerchantMachine::where('machine_id', $id) -> get(['merchant_id','percent','is_owner']) -> toArray();

        return ['machine_id' => $id, 'column_name' => $machine_user_list];
    }
}
